<template>
  <div class="proxy-order-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <el-button class="new-order-btn" plain>新增订单</el-button>
    </div>

    <!-- 店铺信息 -->
    <div class="section-card">
      <div class="section-title">店铺信息</div>
      <div class="form-item">
        <div class="form-label">
          <span class="required">*</span>
          店铺名称：
        </div>
        <el-select
          v-model="addGoodsObj.shop_id"
          placeholder="请选择"
          class="shop-select"
          filterable
          @change="handleShopChange"
        >
          <el-option
            v-for="shop in shopList"
            :key="shop.id"
            :label="shop.name"
            :value="shop.shop_id"
          />
        </el-select>
      </div>

      <div class="form-item">
        <div class="form-label">
          <span class="required">*</span>
          收货地址：
        </div>
        <div class="address-select-wrapper" @click="showAddressDrawer">
          <el-input
            v-model="selectedAddressText"
            placeholder="请选择收货地址"
            readonly
            class="address-input"
          />
        </div>
      </div>
    </div>

    <!-- 采购清单 -->
    <div class="section-card">
      <div class="section-title">采购清单</div>
      <div class="order-table">
        <table>
          <thead>
            <tr>
              <th width="170">品牌</th>
              <th width="300">商品名称</th>
              <th width="300">规格属性</th>
              <th width="120">厂价</th>
              <th width="120">折扣价</th>
              <th width="120">购买数量</th>
              <th width="150">备注</th>
              <th>应付金额</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in addGoodsObj.detail" :key="index">
              <td>
                <el-select
                  v-model="item.brand_id"
                  placeholder="请选择品牌"
                  filterable
                  @change="handleBrandChange(index)"
                >
                  <el-option
                    v-for="item in addGoodsObj.detail[index]?.optionsObj
                      ?.brandList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </td>
              <td>
                <el-select
                  v-model="item.goods_id"
                  placeholder="请选择品牌,再选择商品"
                  filterable
                  @change="handleGoodsChange(index)"
                >
                  <el-option
                    v-for="item in addGoodsObj.detail[index]?.optionsObj
                      ?.goodsList"
                    :key="item.goods_id"
                    :label="item.goods_name"
                    :value="item.goods_id"
                  />
                </el-select>
              </td>
              <td>
                <div>
                  <el-cascader
                    v-model="item.sku_id"
                    :options="addGoodsObj.detail[index]?.optionsObj?.skuList"
                    :props="{
                      expandTrigger: 'hover',
                      emitPath: false,
                      value: 'id',
                      label: 'value',
                      children: 'children',
                      leaf: 'leaf',
                    }"
                    filterable
                    @change="handleSkuChange(index)"
                  />
                </div>
              </td>
              <td>
                {{ item.factory_price || 0 }}
              </td>
              <td>
                <el-input-number
                  v-model="item.price"
                  :min="0"
                  :controls="false"
                  class="quantity-input"
                  @wheel.prevent="stopScroll($event)"
                />
              </td>
              <td>
                <el-input-number
                  v-model="item.quantity"
                  :min="0"
                  :controls="false"
                  class="quantity-input"
                  @wheel.prevent="stopScroll($event)"
                />
              </td>
              <td>
                <el-input
                  v-model="item.remark"
                  type="text"
                  class="remark-input"
                />
              </td>
              <td>¥ {{ (item.price * item.quantity).toFixed(2) }}</td>
              <td>
                <el-button type="danger" @click="deleteItem(index)">
                  删除
                </el-button>
              </td>
            </tr>
          </tbody>
        </table>

        <!-- 添加采购清单按钮 -->
        <div class="add-item-link">
          <el-link type="primary" @click="openSelectGoods">
            +添加采购清单
          </el-link>
        </div>

        <!-- 订单总价 -->
        <div class="order-total">
          <span>下单金额：</span>
          <span class="total-price">¥{{ orderTotal.toFixed(2) }}</span>
        </div>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div class="action-buttons">
      <el-button type="primary" @click="submitOrder" v-repeat>确定</el-button>
      <el-button @click="cancel">取消</el-button>
    </div>

    <!-- 地址选择抽屉 -->
    <el-drawer
      v-model="addressDrawerVisible"
      title="选择收货地址"
      direction="rtl"
      size="30%"
    >
      <div class="address-list">
        <div
          v-for="address in addresses"
          :key="address.id"
          class="address-item"
          :class="{ 'address-selected': selectedAddress === address.id }"
          @click="selectAddress(address.id)"
        >
          <div
            class="address-badge"
            :class="{
              'supplier-badge': address.type === 'supplier',
              'shop-badge': address.type !== 'supplier',
            }"
          >
            {{ address.type === 'supplier' ? '供应商' : '店铺' }}
          </div>
          <div class="address-header">
            <span class="contact-name">{{ address.consignee }}</span>
            <span class="contact-phone">{{ address.mobile }}</span>
          </div>
          <div class="address-content">
            {{ address.address }}
          </div>
        </div>
      </div>
      <div class="drawer-footer">
        <el-button @click="addressDrawerVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAddress">确认选择</el-button>
      </div>
    </el-drawer>
    <!-- <SelectGoods ref="selectGoodsRef" @confirm="handleAddGoods" /> -->
  </div>
</template>

<script setup>
  import { ref, computed, reactive } from 'vue'
  import { ElMessage } from 'element-plus'
  import { getAllStoreList as getStoreList } from '@/api/store'
  import { getAddressList, getDefaultAddress } from '@/api/address'
  import { message, stopScroll } from '@/utils/helper'
  import SelectGoods from '@/components/goods/selectGoods.vue'
  import {
    addSingleProxySubmit,
    getProxyStoreBrandList,
    getProxyStoreGoodsList,
    getProxyStoreSpecList,
  } from '@/api/proxy'
  import { useRouter } from 'vue-router'
  import _ from 'lodash'
  // 店铺选择
  const selectGoodsRef = ref(null)
  const router = useRouter()

  // 地址选择
  const addressDrawerVisible = ref(false)
  const selectedAddress = ref('')
  const selectedAddressText = ref('')
  const addGoodsObj = ref({
    shop_id: undefined,
    supplier_shop_id: undefined,
    address_id: undefined,
    user_remark: '',
    detail: [],
  })

  const goodsDefaultObj = reactive({
    brand_id: undefined,
    brand_name: undefined,
    goods_id: undefined,
    product_name: undefined,
    goods_name: undefined,
    sku_id: undefined,
    quantity: 1,
    goods_spec_value_name: undefined,
    goods_spec_name: undefined,
    goods_value_name: undefined,
    price: '0.00',
    remark: '',
    optionsObj: {
      brandList: [],
      goodsList: [],
      skuList: [],
      goodsPages: 1,
      skuPages: 1,
    },
  })
  const handleShopChange = async (shopId) => {
    const shop = shopList.value.find((item) => item.shop_id === shopId)
    if (shop) {
      addGoodsObj.value.supplier_shop_id = shop.id
    }
    await getAddressDataList()
    await getDefaultAddressData()
    // 清空下发的商品数据 因为折扣是不一样的
    addGoodsObj.value.detail = []
    await getBrandListData()
  }

  const openSelectGoods = () => {
    if (!addGoodsObj.value.supplier_shop_id)
      return message('请选择店铺', 'error')
    // selectGoodsRef.value.open(addGoodsObj.value.supplier_shop_id)
    addGoodsObj.value.detail.push(_.cloneDeep(goodsDefaultObj))
    addGoodsObj.value.detail[
      addGoodsObj.value.detail.length - 1
    ].optionsObj.brandList = _.cloneDeep(brandList.value)
  }

  const addresses = ref([])
  const getAddressDataList = async () => {
    const { data } = await getAddressList({
      supplier_shop_id: addGoodsObj.value.supplier_shop_id,
      page: 1,
      limit: 999,
    })
    addresses.value = data.data.map((address) => {
      return {
        ...address,
        type: address.source || (address.is_supplier ? 'supplier' : 'shop'),
      }
    })
  }

  const showAddressDrawer = () => {
    addressDrawerVisible.value = true
  }

  const selectAddress = (addressId) => {
    selectedAddress.value = addressId
  }

  const confirmAddress = () => {
    if (!selectedAddress.value) {
      ElMessage.warning('请选择一个地址')
      return
    }

    const selected = addresses.value.find(
      (addr) => addr.id === selectedAddress.value
    )
    if (selected) {
      selectedAddressText.value = `${selected.consignee} ${selected.mobile}\n${selected.address}`
      addGoodsObj.value.address_id = selected.id
    }
    addressDrawerVisible.value = false
  }

  // 计算订单总价
  const orderTotal = computed(() => {
    const total = addGoodsObj.value.detail.reduce(
      (sum, item) => sum + item.price * item.quantity,
      0
    )
    return total
  })

  // 提交订单
  const submitOrder = async () => {
    if (!addGoodsObj.value.shop_id) {
      ElMessage.warning('请选择店铺')
      return
    }

    if (!addGoodsObj.value.address_id) {
      ElMessage.warning('请选择收货地址')
      return
    }
    if (addGoodsObj.value.detail.length === 0) {
      ElMessage.warning('请选择商品')
      return
    }
    if (
      addGoodsObj.value.detail.some((item) => !item.quantity || !item.price)
    ) {
      ElMessage.warning('有商品未填写数量或价格')
      return
    }
    const res = await addSingleProxySubmit(addGoodsObj.value)
    ElMessage.success('订单提交成功！')
    cancel()
  }

  // 取消
  const cancel = () => {
    // 可以添加返回逻辑或重置表单
    router.push('/single/singleProxy?replace=true')
  }
  const shopList = ref([])
  const getShopList = async () => {
    const { data } = await getStoreList()
    shopList.value = data
  }

  // const handleAddGoods = (data) => {
  //   addGoodsObj.value.detail = [
  //     ...addGoodsObj.value.detail,
  //     ...data.map((i) => {
  //       const goods_spec_name = i.goods_spec_name.join('??')
  //       const goods_value_name = i.goods_spec_value_name.join('??')
  //       let str = ''
  //       i.goods_spec_name.forEach((item, indexSpe) => {
  //         str += `${item}：${i.goods_spec_value_name[indexSpe]} `
  //       })
  //       const goods_spec_value_name = str
  //       return {
  //         brand_id: i.brand_id,
  //         brand_name: i.brand?.name || '',
  //         goods_id: i.goods_id,
  //         product_name: i.product_name,
  //         goods_name: i.goods_name,
  //         sku_id: i.id,
  //         quantity: 1,
  //         goods_spec_value_name: goods_spec_value_name,
  //         goods_spec_name: goods_spec_name,
  //         goods_value_name: goods_value_name,
  //         price: i.discount_price,
  //         remark: '',
  //       }
  //     }),
  //   ]
  // }
  const deleteItem = (index) => {
    addGoodsObj.value.detail.splice(index, 1)
  }

  const getDefaultAddressData = async () => {
    const { data } = await getDefaultAddress({
      supplier_shop_id: addGoodsObj.value.supplier_shop_id,
    })
    if (data) {
      selectedAddressText.value = `${data.consignee} ${data.mobile}\n${data.address}`
      addGoodsObj.value.address_id = data.id
      // 将默认地址添加到地址列表中，确保有type属性
      if (addresses.value.findIndex((addr) => addr.id === data.id) === -1) {
        addresses.value.unshift({
          ...data,
          type: data.source || (data.is_supplier ? 'supplier' : 'shop'),
        })
      }
      return
    }
    selectedAddressText.value = ``
    addGoodsObj.value.address_id = undefined
  }
  // 获取公用的品牌列表
  const brandList = ref([])
  const getBrandListData = async () => {
    const { data } = await getProxyStoreBrandList({
      supplier_shop_id: addGoodsObj.value.supplier_shop_id,
    })
    brandList.value = data
  }
  // 品牌获取商品列表
  const handleBrandChange = async (index, isCor = false) => {
    const { data } = await getProxyStoreGoodsList({
      brand_id: addGoodsObj.value.detail[index].brand_id,
      page: addGoodsObj.value.detail[index].optionsObj.goodsPages,
      limit: 9999,
    })
    addGoodsObj.value.detail[index].optionsObj.goodsList = _.cloneDeep(
      data.data
    )
    // 是否只是过页
    if (!isCor) {
      addGoodsObj.value.detail[index] = {
        ..._.cloneDeep(goodsDefaultObj),
        brand_id: addGoodsObj.value.detail[index].brand_id,
        optionsObj: {
          brandList: addGoodsObj.value.detail[index].optionsObj.brandList,
          goodsList: addGoodsObj.value.detail[index].optionsObj.goodsList,
          skuList: [],
        },
      }
    }
  }

  const handleGoodsChange = async (index) => {
    const { data } = await getProxyStoreSpecList({
      supplier_shop_id: addGoodsObj.value.supplier_shop_id,
      goods_id: addGoodsObj.value.detail[index].goods_id,
      brand_id: addGoodsObj.value.detail[index].brand_id,
      tree: 1,
    })
    // 处理data.sku
    data.sku.forEach((item) => {
      if (item.children) {
        item.id = item.value
      }
    })
    addGoodsObj.value.detail[index].optionsObj.skuList = _.cloneDeep(data.sku)
    addGoodsObj.value.detail[index] = {
      ..._.cloneDeep(goodsDefaultObj),
      brand_id: addGoodsObj.value.detail[index].brand_id,
      goods_id: addGoodsObj.value.detail[index].goods_id,
      optionsObj: {
        ...addGoodsObj.value.detail[index].optionsObj,
      },
    }
  }

  const handleSkuChange = async (index) => {
    let obj = {}
    addGoodsObj.value.detail[index].optionsObj.skuList.forEach((item) => {
      if (item.id === addGoodsObj.value.detail[index].sku_id) {
        obj = item.data
      }
      if (item.children) {
        item.children.forEach((child) => {
          if (child.id === addGoodsObj.value.detail[index].sku_id) {
            obj = child.data
          }
        })
      }
    })
    const goods_spec_name = obj.goods_spec_name.join('??')
    const goods_value_name = obj.goods_spec_value_name.join('??')
    let str = ''
    obj.goods_spec_name.forEach((item, indexSpe) => {
      str += `${item}：${obj.goods_spec_value_name[indexSpe]} `
    })
    const goods_spec_value_name = str
    addGoodsObj.value.detail[index] = {
      ...addGoodsObj.value.detail[index],
      ...{
        brand_name: obj.brand?.name || '',
        product_name: obj.product_name,
        goods_name: obj.goods_name,
        quantity: 1,
        goods_spec_value_name: goods_spec_value_name,
        goods_spec_name: goods_spec_name,
        goods_value_name: goods_value_name,
        factory_price: obj.factory_price,
        price: obj.discount_price,
        remark: '',
      },
    }
  }
  onMounted(async () => {
    await getShopList()
  })
</script>

<style scoped>
  .proxy-order-container {
    padding: 20px;
    background-color: #f8f8f8;
    min-height: 100vh;
  }

  .page-header {
    margin-bottom: 20px;
    border-bottom: 1px solid #dcdfe6;
  }

  .new-order-btn {
    background: #1890ff;
    color: #f2f2f2;
    padding: 10px 20px;
  }

  .section-card {
    background-color: #fff;
    border-radius: 4px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  }

  .section-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 20px;
    color: #333;
  }

  .form-item {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
  }

  .form-label {
    width: 100px;
    text-align: right;
    margin-right: 10px;
    color: #606266;
  }

  .required {
    color: #f56c6c;
    margin-right: 4px;
  }

  .shop-select {
    width: 300px;
  }

  .address-input {
    width: 600px;
  }

  .address-select-wrapper {
    cursor: pointer;
  }

  .order-table {
    width: 100%;
    overflow-x: auto;
  }

  table {
    width: 100%;
    border-collapse: collapse;
    text-align: center;
  }

  th {
    background-color: #f2f2f2;
    padding: 12px 8px;
    font-weight: normal;
    color: #606266;
    border: 1px solid #ebeef5;
  }

  td {
    padding: 12px 8px;
    border: 1px solid #ebeef5;
    color: #606266;
  }

  .quantity-input,
  .remark-input {
    width: 100%;
  }

  .add-item-link {
    margin: 15px 0;
    text-align: center;
  }

  .order-total {
    text-align: right;
    margin-top: 20px;
    padding-right: 20px;
  }

  .total-price {
    color: #f56c6c;
    font-size: 20px;
    font-weight: bold;
  }

  .action-buttons {
    text-align: center;
    margin-top: 30px;
  }

  .address-list {
    padding: 0 20px;
  }

  .address-item {
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 15px;
    margin-bottom: 15px;
    cursor: pointer;
    transition: all 0.3s;
    position: relative;
    overflow: hidden;
  }

  .address-item:hover {
    border-color: #c6e2ff;
    background-color: #f5f7fa;
  }

  .address-selected {
    border-color: #409eff;
    background-color: #ecf5ff;
  }

  .address-header {
    margin-bottom: 10px;
  }

  .contact-name {
    font-weight: bold;
    margin-right: 10px;
  }

  .contact-phone {
    color: #909399;
  }

  .address-content {
    color: #606266;
    line-height: 1.5;
  }

  .drawer-footer {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 20px;
    display: flex;
    justify-content: flex-end;
    background-color: #fff;
    border-top: 1px solid #ebeef5;
  }

  /* 地址角标样式 */
  .address-badge {
    position: absolute;
    top: 10px;
    right: 0;
    padding: 2px 10px;
    font-size: 12px;
    color: #fff;
    transform: rotate(45deg) translate(15px, -15px);
    transform-origin: center;
    width: 80px;
    text-align: center;
  }

  .supplier-badge {
    background-color: #409eff;
  }

  .shop-badge {
    background-color: #67c23a;
  }
  .custom-pagination {
    position: sticky;
    top: 0px;
    padding-top: 2px;
    background-color: #fff;
    z-index: 999;
    width: 93%;
    margin-bottom: 6px;
  }
</style>
